//
//  DMCCycleImages.m
//  16-UICollectionViewCycleImage
//
//  Created by dllo on 16/8/4.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "DMCCycleImages.h"
#import "UIImageView+DownloadImage.h"
#import "LittleData.h"
#import "Cycle_ViewController.h"
#define kCollectionViewCellReuse @"reuseCycle"
#define kWidth self.bounds.size.width
#define kHeight self.bounds.size.height
@interface DMCCycleImages ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UICollectionView *cycleCollectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation DMCCycleImages

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];
//        [self setUp];
        
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
       self.backgroundColor = [UIColor redColor];
        [self setUp];
           }
    return self;
}
- (void)setUp {
    [self createCollectionView];
    [self createPageControl];
    [self createLabel];
    [self createTimer];
}
#pragma mark - CreateCollectionView
- (void)createCollectionView {
    _layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _layout.minimumLineSpacing = 0;
    _layout.minimumInteritemSpacing = 0;
    _cycleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout: _layout];
    _cycleCollectionView.delegate = self;
    _cycleCollectionView.dataSource = self;
    _cycleCollectionView.pagingEnabled = YES;

    [_cycleCollectionView registerClass:[CDMCycleImageCell class] forCellWithReuseIdentifier:kCollectionViewCellReuse];
    
    _cycleCollectionView.showsHorizontalScrollIndicator = NO;
    [self addSubview:_cycleCollectionView];
    _cycleCollectionView.backgroundColor = [UIColor whiteColor];
}
- (void)setArray:(NSMutableArray *)array {
    _array = array;
    id first = array.firstObject;
    id last = array.lastObject;
    [array addObject:first];
    [array insertObject:last atIndex:0];
    [self createPageControl];
    [_cycleCollectionView reloadData];
}
#pragma mark - CollectionView Datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSLog(@"che 接网科技看看书%ld", _array.count);
    return _array.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    CDMCycleImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCellReuse forIndexPath:indexPath];
//    cell.cycleImage.image = [UIImage imageNamed:_array[indexPath.row]];
    NSString *dataString = _array[indexPath.row];
    [cell.cycleImage asyncDownloadImageWithURL:dataString completionHandler:^(NSData *data, UIImage *image) {
        
    }];
    return cell;
}
#pragma mark - CreatePageControl
- (void)createPageControl {
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    [self addSubview:_pageControl];

}
- (void)createLabel {
    self.label = [[UILabel alloc] initWithFrame:CGRectZero];
    _label.textAlignment = NSTextAlignmentCenter;
    _label.textColor = [UIColor orangeColor];
    _label.font = [UIFont systemFontOfSize:20];
    [self addSubview:_label];
}
#pragma mark - CreateTimer 
- (void)createTimer {
    // 这个创建NSTimer的方式仅仅是创建, 并没有加在runLoop中, 所以需要手动加入RunLoop中
//    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    
    //    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    // 创建一个timer, 并添加到loop中
    // NSRunLoopCommonModes 和NSDefaultRunLoopMode
    // 后者代表默认状态, scheduledTimerWithTimeInterval添加默认状态
    // 前者为多种状态, 包含默认 及 滚动
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    self.timer = timer;
    
}
- (void)nextPage {
    int page = (int)self.pageControl.currentPage;
    if (page == _array.count - 3) {
        page = 0;
    } else {
        page++;
    }
    [self.cycleCollectionView setContentOffset:CGPointMake((page + 1) * CGRectGetWidth(self.bounds), 0)];
    _pageControl.currentPage = page;
    
//    NSIndexPath *currentIndexPath=[[self.cycleCollectionView indexPathsForVisibleItems]lastObject];
//    NSInteger nextItem = currentIndexPath.item + 1;
//    if (nextItem == self.array.count - 2) {
//        nextItem = 0;
//    }
//     NSIndexPath *nextIndexPath=[NSIndexPath indexPathForItem:nextItem inSection:0];
//    [self.cycleCollectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
//    self.pageControl.currentPage = currentIndexPath.row;
}
- (void)removeTimer {
    // 取消timer
    [self.timer invalidate];
    self.timer = nil;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    _cycleCollectionView.frame = self.bounds;
    _layout.itemSize = self.bounds.size;
    [_cycleCollectionView setContentOffset:CGPointMake(kWidth, 0)];
    
    _pageControl.frame = CGRectMake(0, 0, 100, 20);
    _pageControl.center = CGPointMake(kWidth / 2, kHeight - 20);
    _pageControl.numberOfPages = _array.count - 2;
    
    _label.frame = CGRectMake(0, 0, kWidth, 50);
    _label.center = CGPointMake(kWidth / 2, 20);
    
  
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self createTimer];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
   //#warning 直接判断等与0有啥问题
    if (scrollView.contentOffset.x <= _cycleCollectionView.bounds.size.width / 2) {
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:(_array.count - 2) inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else if (scrollView.contentOffset.x >= _cycleCollectionView.bounds.size.width * (_array.count - 1) - 1) {
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    _pageControl.currentPage = scrollView.contentOffset.x / _cycleCollectionView.bounds.size.width - 1;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    Cycle_ViewController *vc = [[Cycle_ViewController alloc] init];
    NSLog(@"点击了第%ld张图片", indexPath.row);

}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


@implementation CDMCycleImageCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.cycleImage = [[UIImageView alloc] initWithFrame:self.bounds];
        [self.contentView addSubview:_cycleImage];
            }
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    
   }

@end
